package com.multitrack.util;

import java.util.ArrayList;
import java.util.Iterator;

import android.os.Handler;

import com.multitrack.datatype.SocketMessage;

public class ThreadManager {

	static ArrayList<Thread> threads = new ArrayList<Thread>();

	public static boolean add(Thread mThread) {
		if (ThreadManager.isInThread(mThread) == true) {
			return false;
		} else {
			threads.add(mThread);
			return true;
		}
	}

	public static boolean excute(CommunicationManager mThread,
			Handler mHandler, SocketMessage msg) {
		
		if (ThreadManager.isInThread(mThread) == false) {
			mThread.setHanlder(mHandler);
			mThread.setMessage(msg);
			ThreadManager.add(mThread);
			mThread.start();
			return true;
			
		} else {
			return false;
			
		}
	}

	public static boolean excute(CommunicationManager mThread,
			Handler mHandler, SocketMessage msg, Object obj) {
		
		if (ThreadManager.isInThread(mThread) == false) {
			mThread.setHanlder(mHandler);
			mThread.setMessage(msg);
			mThread.setObj(obj);
			ThreadManager.add(mThread);
			mThread.start();
			return true;
			
		} else {
			return false;
			
		}
	}

	public static Thread remove(int index) {
		return threads.remove(index);
	}

	public static boolean remove(Object object) {
		return threads.remove(object);
	}

	public static void startAtThread(int index) {
		threads.get(index).start();
	}

	public static void startLast() {
		threads.get(threads.size()).start();
	}

	public static void startAll() {
		Iterator<Thread> iterator = threads.iterator();
		while (iterator.hasNext()) {
			((Thread) iterator.next()).start();
		}
	}

	public static boolean isInThread(Thread mThread) {
		if (mThread == null) {
			return false;
		}

		Iterator<Thread> iterator = threads.iterator();
		while (iterator.hasNext()) {

			if (((Thread) iterator.next()).equals(mThread)) {
				return true;
			}
		}

		return false;
	}

	public static int size() {
		return threads.size();
	}

	public static Thread getThread(CommunicationManager mThread) {
		if (mThread == null) {
			return null;
		}

		Thread findThread;
		
		Iterator<Thread> iterator = threads.iterator();
		while (iterator.hasNext()) {
			findThread = ((Thread) iterator.next());
			if (findThread.equals(mThread)) {
				return findThread;
			}
		}

		return null;
	}
}
